<?php

namespace backend\modules\home\controllers;

use Yii;
use backend\modules\home\models\Article;
use backend\modules\home\models\ArticleSearch;
use backend\modules\home\models\Category;
use yii\web\Controller;
use yii\web\NotFoundHttpException;
use yii\filters\VerbFilter;
use common\components\Upload;

/**
 * ArticleController implements the CRUD actions for Article model.
 */
class ArticleController extends Controller
{
    /**
     * @inheritdoc
     */
    public $enableCsrfValidation = false;

    public function behaviors()
    {
        return [
            'verbs' => [
                'class' => VerbFilter::className(),
                'actions' => [
                    'delete' => ['POST'],
                ],
            ],
        ];
    }

    public function actions(){
        return [
            'ueditor'=>[
                'class' => 'common\widgets\ueditor\UeditorAction',
                'config'=>[
                    //上传图片配置
                    'imageUrlPrefix' => Yii::$app->params['imgurl'], /* 图片访问路径前缀 */
                    'imagePathFormat' => "/image/{yyyy}{mm}{dd}/{time}{rand:6}", /* 上传保存路径,可以自定义保存路径和文件名格式 */
                ]
            ]
        ];
    }

    /**
     * Lists all Article models.
     * @return mixed
     */
    public function actionIndex()
    {
        $searchModel = new ArticleSearch();
        $dataProvider = $searchModel->search(Yii::$app->request->queryParams);

        return $this->render('index', [
            'searchModel' => $searchModel,
            'dataProvider' => $dataProvider,
        ]);
    }

    /**
     * Displays a single Article model.
     * @param integer $id
     * @return mixed
     * @throws NotFoundHttpException if the model cannot be found
     */
    public function actionView($id)
    {
        return $this->render('view', [
            'model' => $this->findModel($id),
        ]);
    }

    /**
     * Creates a new Article model.
     * If creation is successful, the browser will be redirected to the 'view' page.
     * @return mixed
     */
    public function actionCreate()
    {
        $model = new Article();


        $catelist = Category::find()
        ->where(['cid' => 12])
        ->select('title,id')
        ->indexBy('id')
        ->column();
        $catelist[0] = '无';
        ksort($catelist);

        if ( $model->load(Yii::$app->request->post()) ) {

            if($model->save()){
                return $this->redirect(['view', 'id' => $model->id]);
            }else{
                echo "<pre>";
                print_r($model->errors);exit;
            }
            
        }

        return $this->render('create', [
            'model' => $model,
            'catelist' => $catelist,
        ]);
    }

    /**
     * Updates an existing Article model.
     * If update is successful, the browser will be redirected to the 'view' page.
     * @param integer $id
     * @return mixed
     * @throws NotFoundHttpException if the model cannot be found
     */
    public function actionUpdate($id)
    {
        $model = $this->findModel($id);

        $catelist = Category::find()
        ->where(['cid' => 12])
        ->select('title,id')
        ->indexBy('id')
        ->column();

        $catelist[0] = '无';
        ksort($catelist);

        if ($model->load(Yii::$app->request->post()) && $model->save()) {
            return $this->redirect(['view', 'id' => $model->id]);
        }

        return $this->render('update', [
            'model' => $model,
            'catelist' => $catelist,
        ]);
    }

    /**
     * Deletes an existing Article model.
     * If deletion is successful, the browser will be redirected to the 'index' page.
     * @param integer $id
     * @return mixed
     * @throws NotFoundHttpException if the model cannot be found
     */
    public function actionDelete($id)
    {
        $model = $this->findModel($id);
        if($model->appendix){
            $per_path = getcwd();
            $per_path = str_replace('backend','frontend',$per_path);
            $delete_path =$per_path . $model->appendix;
            @unlink($delete_path);
        }
        $model->delete();

        return $this->redirect(['index']);
    }

    public function actionUploadFile($id){
        $model = $this->findModel($id);
        if (Yii::$app->request->isPost) {
            // 删除旧文件
            $file = Article::findOne(['id' => $id]);
            if(!empty($file->appendix)){
                $per_path = getcwd();
                $per_path = str_replace('backend','frontend',$per_path);
                $delete_path =$per_path . $file->appendix;
                @unlink($delete_path);
            }
            $res = (new Upload)->uploadfilefront();

            if($res['code'] == 200){
                $model->appendix = $res['data'];
                if(!$model->update()){
                    echo "<pre>";
                    print_r($model->errors);exit;
                }
            }
        }
        return $this->render('upload-file', [
            'model' => $model,
        ]);
    }

    /**
     * Finds the Article model based on its primary key value.
     * If the model is not found, a 404 HTTP exception will be thrown.
     * @param integer $id
     * @return Article the loaded model
     * @throws NotFoundHttpException if the model cannot be found
     */
    protected function findModel($id)
    {
        if (($model = Article::findOne($id)) !== null) {
            return $model;
        }

        throw new NotFoundHttpException('The requested page does not exist.');
    }
}
